package com.alan.wlmediaplayer.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lib.basex.image.LImageBuilder;
import com.lib.basex.utils.LBitmapUtils;
import com.lib.basex.utils.LFileUtils;
import com.lib.basex.utils.LPathUtils;
import com.lib.basex.utils.LUtils;
import com.lib.basex.utils.Logger;

import java.io.File;
import java.util.HashMap;

/**
 * @author Alan
 * 时 间：11/3/21
 * 简 述：<功能简述>
 */
public class VideoImageView extends androidx.appcompat.widget.AppCompatImageView {

    boolean isGet = false;

    public VideoImageView(@NonNull Context context) {
        super(context);
    }

    public VideoImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void get(String url,String tag) {
        if (setImageFile(tag)) {
            return;
        }
        new Thread(() -> {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(url, new HashMap<>());
                Bitmap bitmap = retriever.getFrameAtTime();

                if (null != bitmap) {
                    save(bitmap, tag);
                    post(() -> {
                        setImageBitmap(bitmap);
                        isGet = true;
                    });
                }
            } catch (Exception e) {
                Logger.error(e);
            } finally {
                retriever.release();
            }
        }).start();
    }

    public boolean isGet() {
        return isGet;
    }

    public boolean setImageFile(String url) {
        String name = LFileUtils.getFilenameByKeyHashCode(url);
        String path = LPathUtils.getDir() + "/image/" + name;
        if (new File(path).exists()) {
            LImageBuilder builder = new LImageBuilder();
            builder.setPath(path);
            builder.build(this);
            return true;
        }
        return false;
    }

    private void save(Bitmap bitmap, String url) {
        String name = LFileUtils.getFilenameByKeyHashCode(url);
        String path = LPathUtils.getDir() + "/image/" + name;
        LBitmapUtils.save(bitmap, path);
    }
}
